package com.library.management.controller;

import com.library.management.dto.UserCreateDTO;
import com.library.management.dto.UserInfoDTO;
import com.library.management.dto.UserPageDTO;
import com.library.management.dto.UserUpdateDTO;
import com.library.management.service.UsersService;
import com.library.management.util.Result;
import cn.dev33.satoken.annotation.SaCheckRole;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiImplicitParam;
import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;

/**
 * 用户管理控制器
 */
@Slf4j
@RestController
@RequestMapping("/api/users")
@Api(tags = "用户管理接口", description = "提供用户的增删改查接口")
public class UserController {

    @Autowired
    private UsersService usersService;

    /**
     * 查询用户列表（分页）
     * @param pageDTO 分页和搜索参数
     * @return 用户列表数据
     */
    @ApiOperation("查询用户列表")
    @SaCheckRole("admin")
    @GetMapping
    public Result<Page<UserInfoDTO>> getUserList(UserPageDTO pageDTO) {
        log.info("获取用户列表: pageNum={}, pageSize={}, keyword={}", 
                pageDTO.getPageNum(), pageDTO.getPageSize(), pageDTO.getKeyword());
        Page<UserInfoDTO> userPage = usersService.getUserPage(pageDTO);
        return Result.success(userPage);
    }

    /**
     * 创建用户
     * @param userCreateDTO 用户创建参数
     * @return 创建后的用户信息
     */
    @ApiOperation("创建用户")
    @SaCheckRole("admin")
    @PostMapping
    public Result<UserInfoDTO> createUser(@RequestBody @Validated UserCreateDTO userCreateDTO) {
        log.info("创建用户: {}", userCreateDTO.getUsername());
        UserInfoDTO userInfoDTO = usersService.createUser(userCreateDTO);
        return Result.success(userInfoDTO);
    }

    /**
     * 修改用户信息
     * @param id 用户ID
     * @param userUpdateDTO 更新参数
     * @return 更新后的用户信息
     */
    @ApiOperation("修改用户信息")
    @ApiImplicitParam(name = "id", value = "用户ID", required = true, dataType = "Integer", paramType = "path")
    @SaCheckRole("admin")
    @PutMapping("/{id}")
    public Result<UserInfoDTO> updateUser(@PathVariable Integer id, @RequestBody UserUpdateDTO userUpdateDTO) {
        log.info("修改用户: id={}", id);
        UserInfoDTO userInfoDTO = usersService.updateUser(id, userUpdateDTO);
        return Result.success(userInfoDTO);
    }

    /**
     * 删除用户
     * @param id 用户ID
     * @return 操作结果
     */
    @ApiOperation("删除用户")
    @ApiImplicitParam(name = "id", value = "用户ID", required = true, dataType = "Integer", paramType = "path")
    @SaCheckRole("admin")
    @DeleteMapping("/{id}")
    public Result<Boolean> deleteUser(@PathVariable Integer id) {
        log.info("删除用户: id={}", id);
        boolean result = usersService.deleteUser(id);
        return Result.success(result);
    }
} 